package main.java.easy;

import main.java.structure.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Author: 郑国荣
 * @Date: 2023-07-30-12:25
 * @Description: 二叉树中序遍历
 */
public class SequenceTraversal {

    /**
     * 递归算法
     * @param root
     * @return
     */
    public static List<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        inOrder(root,list);
        return list;
    }
    public static void inOrder(TreeNode root,List<Integer> list){
        if (root == null) return;
        inOrder(root.left,list);
        list.add(root.val);
        inOrder(root.right,list);

    }

    /**
     * 迭代算法
     */
    public static List<Integer> inorderTraversalByInter(TreeNode root){
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()){
            while (root!=null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            list.add(root.val);
            root = root.right;
        }
        return list;
    }


    public static void main(String[] args) {
        // 创建二叉树

        TreeNode root = new TreeNode(1,new TreeNode(2,new TreeNode(4),new TreeNode(5)),new TreeNode(3));
        // 调用中序遍历方法
        List<Integer> result = inorderTraversalByInter(root);

        // 输出遍历结果
        for (int num : result) {
            System.out.print(num + " ");
        }


    }
}
